import React from 'react';
import config from 'config';
import moment from 'moment';
import configureStore from "stores";
import { connect } from 'react-redux';
import httpFetch from 'share/httpFetch';
import menuRoute from "routes/menuRoute";
import Chooser from "components/chooser";
import SearchArea from 'components/search-area';
import ResizeTable from 'components/resize-table'
import 'styles/financial-payment/confirm-payment.scss';
import { setFinancePayment, setExtraSearch } from "actions/cache";
import ImportModal from "components/template/import-modal-ie/import-modal";
import {messages, dealCache, deepFullCopy, queryCurrencyPrecision, deepCopy} from 'share/common';
import CompanyBankSelector from 'containers/financial-management/confirm-payment/company-bank-selector';
import confirmPaymentService from 'containers/financial-management/confirm-payment/confirm-payment.service';
import DepartmentPicker from 'containers/financial-management/wait-for-billing/new-billing/department-picker';
import { Tabs, Button, notification, Icon, Popover, Modal, Form, Input, message, Col, Select, Dropdown, Menu } from 'antd';
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
const TextArea = Input.TextArea;

class ConfirmPayment extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      status: 'prending_pay',
      tabs: [
        {key: 'prending_pay', name:messages('financial-management.key172'/*待确认*/)},
        {key: 'pay_in_process', name:messages('financial-management.key173'/*待付款*/)},
        {key: 'pay_finished', name:messages('financial-management.key174'/*已付款*/)},
        this.checkFunctionProfiles(['finance.payment.cancel'], [true]) && {key: 'pay_cancel', name:messages('financial-management.key567')/*支付取消*/}
      ],
      searchForm: [
        {
          type: 'radio',
          id: 'type',
          label: messages('financial-management.key133'/*单据类型*/),
          options: [
            {label: messages('financial-management.key160'/*报销单*/), value: 'INVOICE'},
            {label: messages('financial-management.key161'/*借款单*/), value: 'BORROW'}],
          event: 'CHANGE_TYPE',
          defaultValue: 'INVOICE'
        },
        {
          type: 'searcher',
          id: 'formOids',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 1002}
        },
        {
          type: 'items',
          id: 'dateRange',
          items: [
            {type: 'date', id: 'submittedDateStart', label: messages('financial-management.key162'/*日期从*/),defaultValue:moment().subtract(3, 'month')},
            {type: 'date', id: 'submittedDateEnd', label: messages('financial-management.key163'/*日期至*/),defaultValue:moment()}
          ]
        },
        {
          type: 'combobox', id: 'businessCode', label: messages('financial-management.key134'/*单号*/),
          placeholder: messages('common.please.enter') + messages('financial-management.key134'/*单号*/),
          options: [],
          searchUrl: `${config.baseUrl}/api/expense/report/search`,
          method: 'get',
          searchKey: 'keyword', getParams: {status: 'prending_pay'}, labelKey: '_self', valueKey: '_self'
        },
        {
          type: 'combobox',
          id: 'applicantOid',
          label: messages('financial-management.key131')/*申请人*/,
          placeholder: messages('common.please.enter') + messages('financial-management.key165'/*姓名／工号*/),
          options: [],
          searchUrl: `${config.baseUrl}/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          method: 'get',
          searchKey: 'keyword',
          labelKey: 'fullName',
          valueKey: 'userOID',
          renderOption: option => (`${option.eid}-${option.employeeID}-${option.fullName}${(option.status !== 1001 ? (
            `（${option.status === 1002 ? messages('financial-management.key622')/*待离职员工*/ : messages('financial-management.key623')/*离职员工*/}）`
          ) : '')}`)
        },
        {
          type: 'multiple',
          id: 'corporationOids',
          label: messages('financial-management.key128'/*法人实体*/),
          options: [],
          getUrl: `${config.baseUrl}/api/v2/my/company/receipted/invoices?page=0&size=100`,
          method: 'get',
          labelKey: 'companyName',
          valueKey: 'companyReceiptedOID'
        },
        {
          type: 'list',
          id: 'companyIds',
          label: messages('financial-management.key588')/*公司*/,
          labelKey: 'name',
          valueKey: 'id',
          listType: 'permission_company',
          listExtraParams:{enabled: true},
          single: true
        }
      ],
      nowType: 'INVOICE',
      searchParams: {
        status: "prending_pay",
        submittedDateStart: moment(moment().subtract(3, 'month').format('YYYY-MM-DD 00:00:00')).utc(),
        submittedDateEnd: moment(moment().format('YYYY-MM-DD 23:59:59')).utc()
      },
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('financial-management.key166'/*序号*/), dataIndex: 'index', width: 72, render: (value, record, index) =>
            this.state.pageSize * this.state.page + index + 1},
        {title: messages('financial-management.key131'/*申请人*/), dataIndex: 'applicantName', width: '8%'},
        {title: messages('financial-management.key130'/*工号*/), dataIndex: "applicantEmployeeId", width: '7%'},
        {title: messages('financial-management.key132'/*提交日期*/), dataIndex: 'lastSubmittedDate', width: 100, render: date => moment(date).local().format('YYYY-MM-DD'), sorter: true},
        {title: messages('financial-management.key133'/*单据类型*/), dataIndex: 'formName', width: '10%', render: formName => (
            <Popover content={formName}>
              {formName}
            </Popover>
          ), sorter: true},
        {title: messages('financial-management.key134')/*单号*/ , dataIndex: 'businessCode', width: '8%', render: (text, record) => {
            const { nowType } = this.state;
            let showText = record.parentBusinessCode ?
              (nowType !== 'pay_cancel' ? `${record.parentBusinessCode}-${text}` : `${record.parentBusinessCode}-${record.childBusinessCode}`) :
              (nowType !== 'pay_cancel' ? text : record.childBusinessCode);
            return (
              <Popover content={showText}>
                {showText}
              </Popover>
            )
          }, sorter: true},
        {title: messages('financial-management.key589')/*收款方类型*/, dataIndex: 'payeeType', width: '15%', render: value => {return value === 1001 ? messages('financial-management.key307')/*供应商*/ : messages('financial-management.key164')/*员工*/}},
        {title: messages('financial-management.key590')/*收款方*/, dataIndex: 'payeeName', width: '8%'},
        {title: messages('financial-management.key591')/*收款账号*/, dataIndex: 'accountNumber', width: '10%',render: value => (
            <Popover content={value}>
              {value}
            </Popover>
          )},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 72},
        {title: messages('financial-management.key169'/*待支付金额*/), dataIndex: 'realPaymentAmount', render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode)), align: "right", sorter: true},
        {title: messages('financial-management.key170'/*凭证编号*/), width: 1,dataIndex: 'origDocumentSequence', render: origDocumentSequence => (
            <Popover content={origDocumentSequence ? origDocumentSequence : '-'}>
              {origDocumentSequence  ? origDocumentSequence : '-'}
            </Popover>
          )}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      selectedDataItems: [],
      selectedDataNum: 0,
      rowSelection: {
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      showCompanyBank: false,
      confirmLoading: false,
      expenseDetailRouter: menuRoute.getRouteItem('expense-report-detail-payment'),
      loadDetailRouter: menuRoute.getRouteItem('loan-detail-payment'),
      dropDownSelectedKeys: "CURRENT_PAGE",
      buttonRoleSwitch: this.checkPageRole('EXPENSEPAYMENT', 2),
      cancelPayModal: false,
      cancelLoading: false,
      buttonCancel: false,
      payeeType: null,
      departmentOids: [],
      payeeId: [],
      sortDTOs: [],
      allPageRecord: []
    };
  }

  componentWillMount(){
    this.getCache();
  };

  renderTabs(){
    return (
      this.state.tabs.map(tab => {
        if(typeof tab === 'object'){
          let returnObject = <TabPane tab={tab.name} key={tab.key}/>;
          return returnObject;
        }
      })
    )
  };

  //表单头处理
  handleTableColumns = () => {
    let { columns, status, nowType, tabs } = this.state;
    if(nowType === 'BORROW'){
      tabs.map((item,index) => {
        item.key === 'pay_cancel' && (tabs[index] = undefined);
      });
      tabs = tabs.filter(item => !!item);
    }
    columns.filter(item => item.dataIndex === "realPaymentAmount")[0].title = status === 'pay_finished' ? messages('financial-management.key175'/*已支付金额*/) : (status === 'pay_cancel' ? messages('financial-management.key568')/*取消支付金额*/ : messages('financial-management.key169'/*待支付金额*/));
    if(status === 'pay_cancel'){
      columns.filter(item => item.dataIndex === 'reason').length === 0 && columns.push({title: messages('financial-management.key569')/*取消理由*/, dataIndex: 'reason', width: '10%'});
    }else{
      columns.map((item,index) => {
        item.dataIndex === 'reason' && (columns[index] = undefined);
      });
      columns = columns.filter(item => !!item);
    }
    this.setState({columns, tabs});
  };

  //Tab点击事件
  onChangeTabs = (key) => {
    let { searchParams } = this.state;
    searchParams.status = key;
    this.setState({
      searchParams,
      page: 0,
      status: key
    },() => {
      this.handleSearchForm();
      this.handleTableColumns();
      this.clearRowSelection();
      this.formRef.handleSearch();
    });
  };

  //渲染处理数据源
  handleSearchForm = () => {
    let { nowType, status, searchForm } = this.state;
    searchForm.map((item,index) => {
      if(item.id === 'businessCode'){
        let url = config.baseUrl;
        if (nowType === 'INVOICE') {
          url += `/api/expense/report/search`;
        } else {
          url += `/api/loanBill/query/business/code/by/keyword`
        }
        item.searchUrl = url;
        item.getParams = {status};
      }else if(item.id === 'formOids'){
        let temp = {};
        if (nowType === 'INVOICE') {
          temp.formType = 1002;
        } else {
          temp.formType = 3001;
        }
        item.listExtraParams = temp;
      }else if(index === 0){
        if(status === 'pay_cancel'){
          item.options = [
            {label: messages('financial-management.key160'/*报销单*/), value: 'INVOICE'}
          ];
        }else{
          item.options = [
            {label: messages('financial-management.key160'/*报销单*/), value: 'INVOICE'},
            {label: messages('financial-management.key161'/*借款单*/), value: 'BORROW'}
          ];
        }
      }
    });
    this.setState({searchForm})
  };

  //得到对应单据列表数据
  getList = () => {
    const{ searchParams, status, pagination } = this.state;
    let url = '';
    if(this.state.nowType === 'INVOICE'){
      switch (status){
        case 'prending_pay':
          url = `${config.baseUrl}/api/payment/schedule/query/pending/confirm`;
          break;
        case 'pay_in_process':
          url = `${config.baseUrl}/api/payment/schedule/query/pending/pay`;
          break;
        case 'pay_finished':
          url = `${config.baseUrl}/api/payment/schedule/query/paid`;
          break;
        default:
          url = `${config.baseUrl}/api/v2/expense/reports/finance/admin/search`;
          break;
      }
    }else{
      switch (status){
        case 'prending_pay':
          url = `${config.baseUrl}/api/loan/line/query/pending/confirm`;
          break;
        case 'pay_in_process':
          url = `${config.baseUrl}/api/loan/line/query/pending/pay`;
          break;
        default:
          url = `${config.baseUrl}/api/loan/line/query/paid`;
          break;
      }
    }
    let temp = deepFullCopy(searchParams);
    temp.page = this.state.page;
    temp.status !== 'pay_cancel' && delete temp.status;
    temp.size = this.state.pageSize;
    temp.status !== 'pay_cancel' && (temp.sortDTOs = this.state.sortDTOs);
    this.setState({loading: true});
    return httpFetch.post(url, temp).then((response)=>{
      pagination.total = status === 'pay_cancel' ? Number(response.headers['x-total-count']) : Number(response.data.total);
      pagination.current = this.state.page + 1;
      this.setState({
        data: status === 'pay_cancel' ? response.data : response.data.rows,
        loading: false,
        current: this.state.page + 1,
        pagination
      }, ()=>{
        this.refreshRowSelection()
      })
    }).catch(e => {
      this.setState({loading: false});
      message.error(e.response.data.message);
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      })
  };

  //搜索
  search = (result) => {
    const { status, page, departmentOids, payeeType, payeeId } = this.state;
    let temp = deepCopy(result);
    temp.tabsStatus = status;
    temp.page = page;
    configureStore.store.dispatch(setFinancePayment(temp));
    configureStore.store.dispatch(setExtraSearch({departmentOids,payeeType,payeeId}));
    result.submittedDateStart && (result.submittedDateStart = moment(result.submittedDateStart.format('YYYY-MM-DD 00:00:00')).utc());
    result.submittedDateEnd && (result.submittedDateEnd = moment(result.submittedDateEnd.format('YYYY-MM-DD 23:59:59')).utc());
    let departmentOID = [];
    departmentOids.map(item => {
      departmentOID.push(item.value);
    });
    let id = null;
    payeeId.map(item => {
      id = item.id;
    });
    let searchParams = {
      applicantOid: result.applicantOid,
      businessCode: result.businessCode,
      corporationOids: result.corporationOids,
      submittedDateEnd: result.submittedDateEnd,
      submittedDateStart: result.submittedDateStart,
      status: status,
      formOids: result.formOids,
      companyIds: result.companyIds,
      departmentOids: departmentOID,
      payeeType,
      payeeId: id
    };
    this.setState({
      searchParams: searchParams,
      page: result.page ? result.page : 0,
    }, () => {
      this.clearRowSelection();
      this.getList();
    })
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.financePayment;
    let extra = this.props.extraSearch;
    if(Object.keys(result).length > 0 || Object.keys(extra).length > 0){
      this.dealCache(result,extra);
    }else{
      this.getList();
    }
  };

  //处理筛选缓存数据
  dealCache = (result,extra) => {
    let { status, searchForm, nowType, page } = this.state;
    if (Object.keys(result).length > 0) {
      status = result.tabsStatus;
      nowType = result.type;
      page = result.page;
      dealCache(searchForm, result);
      if(Object.keys(extra).length === 0){
        this.setState({ status, nowType, searchForm, page }, () => {
          let temp = deepCopy(result);
          temp.submittedDateStart && (temp.submittedDateStart = moment(temp.submittedDateStart));
          temp.submittedDateEnd && (temp.submittedDateEnd = moment(temp.submittedDateEnd));
          this.search(temp);
          this.handleTableColumns();
          configureStore.store.dispatch(setFinancePayment({}));
          configureStore.store.dispatch(setExtraSearch({}));
        })
      }else{
        this.setState({
          departmentOids: extra.departmentOids,
          payeeType: extra.payeeType,
          payeeId: extra.payeeId,
          status, nowType, searchForm, page
        },() => {
          this.search({});
          this.handleTableColumns();
          configureStore.store.dispatch(setFinancePayment({}));
          configureStore.store.dispatch(setExtraSearch({}));
        })
      }
    }else{
      this.setState({
        departmentOids: extra.departmentOids,
        payeeType: extra.payeeType,
        payeeId: extra.payeeId,
      },() => {
        this.search({});
        this.handleTableColumns();
        configureStore.store.dispatch(setFinancePayment({}));
        configureStore.store.dispatch(setExtraSearch({}));
      })
    }
  };

  //清空搜索区域
  clear = () => {
    configureStore.store.dispatch(setFinancePayment({}));
    configureStore.store.dispatch(setExtraSearch({}));
    let forms = ['dateRange'];
    let { searchForm } = this.state;
    searchForm.map(item => {
      if(~forms.indexOf(item.id)){
        item.items.map(dateItem => {
          delete dateItem.defaultValue;
        });
      }
    });
    this.setState({
      searchForm,
      searchParams: {
        status: this.state.status
      },
      nowType: 'INVOICE',
      dropDownSelectedKeys: 'CURRENT_PAGE',
      departmentOids: [],
      payeeType: null,
      payeeId: []
    }, () => {
      this.handleSearchForm();
      this.handleTableColumns();
      this.isNeedCancelPay();
      this.getList();
    })
  };

  //搜索区域点击事件
  searchEventHandle = (event, value, valuesTmp) => {
    switch(event){
      case 'CHANGE_TYPE': {
        if(value === this.state.nowType)
          return;
        this.setState({ page: 0,dropDownSelectedKeys:'CURRENT_PAGE', nowType: value }, ()=>{
          this.formRef.setValues({
            formOids: undefined
          });
          valuesTmp.formOids = undefined;
          valuesTmp.formOidsLable = undefined;
          valuesTmp.type = value;
          valuesTmp.typeLable = value;
          this.isNeedCancelPay();
          this.clearRowSelection();
          this.handleSearchForm();
          this.search(valuesTmp);
        });
        break;
      }
    }
  };

  isNeedCancelPay = () => {
    const { nowType, tabs } = this.state;
    if(nowType === 'INVOICE'){
      this.checkFunctionProfiles(['finance.payment.cancel'], [true]) && tabs.filter(item => item.key === 'pay_cancel').length === 0 && tabs.push({key: 'pay_cancel', name:messages('financial-management.key567')/*支付取消*/});
    }else{
      tabs.filter(item => item.key === 'pay_cancel').length > 0 && tabs.pop();
    }
    this.setState({tabs});
  };

  //跳转单据详情
  handleRowClick = (record) => {
    const { nowType, status, expenseDetailRouter, loadDetailRouter } = this.state;
    let url = '';
    if(nowType === 'INVOICE')
      url = expenseDetailRouter.url.replace(':expenseReportOID', record.entityOid || record.expenseReportOID ).replace(':backType','history');
    else
      url = loadDetailRouter.url.replace(':formOID', record.formOid).replace(':loanBillOID', record.entityOid).replace(':backType','history');
    status === 'prending_pay' && (url += `?prending_pay=true`);
    status === 'pay_in_process' && (url += `?pay_in_process=true`);
    this.context.router.push(url);
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    let { dropDownSelectedKeys, selectedDataNum, rowSelection, selectedDataItems } = this.state;
    if(dropDownSelectedKeys !== 'CURRENT_PAGE'){
      if(!selected){
        selectedDataItems.push(record);
        selectedDataNum -= 1;
      } else {
        selectedDataItems.map((selected, index) => {
          if(record.id === selected.id){
            selectedDataItems.splice(index, 1);
          }
        });
        selectedDataNum += 1;
      }
    }
    else{
      if(!selected){
        selectedDataItems.map((selected, index) => {
          if(record.id === selected.id){
            selectedDataItems.splice(index, 1);
            selectedDataNum -= 1;
          }
        });
      } else {
        selectedDataItems.push(record);
        selectedDataNum += 1;
      }
    }
    this.setState({ selectedDataNum, rowSelection, selectedDataItems});
  };

  //选择当页全部时的判断
  onSelectAll = (selected, selectedRows, changeRows) => {
    let { dropDownSelectedKeys, selectedDataNum, selectedDataItems } = this.state;
    if(dropDownSelectedKeys !== 'CURRENT_PAGE'){
      if(!selected){
        changeRows.map(item => {
          selectedDataItems.addIfNotExist(item);
        });
        selectedDataNum = selectedDataNum - changeRows.length;
      } else {
        changeRows.map(item => {
          selectedDataItems.delete(item);
        });
        selectedDataNum = selectedDataNum + changeRows.length;
      }
    } else {
      if (!selected) {
        changeRows.map(item => {
          selectedDataItems.delete(item);
        });
      } else {
        selectedRows.map(item => {
          selectedDataItems.addIfNotExist(item);
        });
      }
      selectedDataNum = selectedDataItems.length;
    }
    this.setState({ selectedDataNum, selectedDataItems});
  };

  renderExpandedRow = (title, content) => {
    return (
      <div>
        <span>{title}</span>:
        <span>{content}</span>
      </div>
    )
  };

  renderAllExpandedRow = (record) =>{
    let result = [];
    if(record.warningList){
      let warningList=JSON.parse(record.warningList);
      let content = '';
      warningList.map(item => {
        if (item.showFlag) {
          content += item.title + '/'
        }
      });
      content && result.push(this.renderExpandedRow(messages('common.label'), content.substr(0, content.length - 1)));
    }
    if(record.printFree){
      result.push(this.renderExpandedRow(messages('common.print.free'), messages('common.print.require')));
    }
    if(result.length>0){
      return result;
    }else{
      return null;
    }
  };

  //换页后根据OIDs刷新选择框
  refreshRowSelection(){
    let { selectedDataItems, data, rowSelection ,dropDownSelectedKeys } = this.state;
    let nowSelectedRowKeys = [];
    if (dropDownSelectedKeys === 'CURRENT_PAGE') {
      selectedDataItems.map(selected => {
        data.map(item => {
          if (selected.id === item.id)
            nowSelectedRowKeys.push(item.id)
        })
      });
      rowSelection.selectedRowKeys = nowSelectedRowKeys;
    } else {
      data.map(item => {
        rowSelection.selectedRowKeys.addIfNotExist(item.id);
      });
    }
    this.setState({rowSelection});
  }

  //全选当页或全选全部
  renderDropDown(){
    return (
      <Menu onClick={this.dropDownChange}	>
        <Menu.Item key="CURRENT_PAGE">{messages('financial-management.key177'/*全选当页*/)}</Menu.Item>
        <Menu.Item key="ALL_PAGE">{messages('financial-management.key178'/*全选全部*/)}</Menu.Item>
      </Menu>
    )
  };

  //全选菜单更改
  dropDownChange = (item) => {
    let { rowSelection, dropDownSelectedKeys, data } = this.state;
    if (dropDownSelectedKeys === item.key) {
      return;
    }
    rowSelection.selectedRowKeys = [];
    let selectedDataNum = 0;
    if (item.key !== 'CURRENT_PAGE') {
      selectedDataNum = this.state.pagination.total;
      rowSelection.selectedRowKeys = this.getSelectId(data);
    }
    this.setState({
      selectedDataItems: [],
      allPageRecord: data,
      selectedDataNum: selectedDataNum,
      dropDownSelectedKeys: item.key,
      rowSelection: rowSelection
    });
  };

  //分页时将单据都push到tempoOID,用于判断分页时单据是否为选中状态
  getSelectId = (data) => {
    var tempOID = [];
    tempOID = data.map(item => {
      return item.id;
    });
    return tempOID;
  };

  //清空选择框
  clearRowSelection(){
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = [];
    this.setState({
      rowSelection: rowSelection,
      selectedDataNum: 0,
      selectedDataItems : [],
      dropDownSelectedKeys:'CURRENT_PAGE'
    });
  }

  //提交成功
  confirmSuccess(isSubmit = true,data = {}){
    if(isSubmit){
      if(data.failNum) {
        notification.open({
          message: messages('financial-management.key151'/*确认付款失败*/),
          description: messages('financial-management.key621',{arg1:data.successNum,arg2:data.failNum})/*付款成功{arg1}条，失败{arg2}条*/,
          icon: <Icon type="frown-circle" style={{color: '#e93652'}}/>,
        });
      } else {
        notification.open({
          message: messages('financial-management.key840')/*发起支付成功*/,
          description: messages('financial-management.key841')/*请稍后确认支付结果*/,
          icon: <Icon type="smile-circle" className='default-color-font'/>,
        });
      }
    }
    this.clearRowSelection();
    this.getList();
  }

  getSubmitData = () => {
    let selectedEntityOIDs = [], excludedEntityOIDs = [], departmentOID = [], entityType = 1002, temp = null;
    let { selectedDataItems, searchParams, payeeType, payeeId, departmentOids, dropDownSelectedKeys } = this.state;
    if(this.state.dropDownSelectedKeys === 'CURRENT_PAGE'){
      selectedEntityOIDs = this.getSelectId(selectedDataItems);
    }else{
      excludedEntityOIDs = this.getSelectId(selectedDataItems);
    }
    if(this.state.nowType !== 'INVOICE'){
      entityType = 3001;
    }
    payeeId.map(item => {
      temp = item.id;
    });
    departmentOids.map(item => {
      departmentOID.push(item.value);
    });
    return {
      currentPageIds: selectedEntityOIDs,
      entityType: entityType,
      excludeIds: excludedEntityOIDs,
      modelEnum: dropDownSelectedKeys,
      submittedDateStart: searchParams.submittedDateStart ? searchParams.submittedDateStart : null,
      submittedDateEnd: searchParams.submittedDateEnd ? searchParams.submittedDateEnd : null,
      businessCode: searchParams.businessCode ? searchParams.businessCode : null,
      comment: null,
      corporationOids: searchParams.corporationOids ? searchParams.corporationOids : [],
      formOids: searchParams.formOids ? searchParams.formOids : [],
      applicantOid: searchParams.applicantOid ? searchParams.applicantOid : null,
      companyIds: searchParams.companyIds ? searchParams.companyIds : [],
      payeeType,
      payeeId: temp,
      departmentOids: departmentOID
    }
  };

  //提交
  submit = () => {
    confirmPaymentService.confirmPayment(this.state.status, this.getSubmitData()).then((res)=>{
      this.setState({confirmLoading: false});
      this.confirmSuccess(true,res.data);
    }).catch((e)=>{
      this.setState({confirmLoading: false});
      if(e.response.data.errorCode){
        notification.open({
          message: messages('financial-management.key151'/*确认付款失败*/),
          description: e.response.data.message,
          icon: <Icon type="frown-circle" style={{ color: '#e93652' }} />,
        });
      }
      else{
        if(e.name === 'SyntaxError')
          this.confirmSuccess();
        else
          notification.open({
            message: messages('financial-management.key151'/*确认付款失败*/),
            description: messages('common.error'/*可能是服务器出了点问题:(*/),
            icon: <Icon type="frown-circle" style={{ color: '#e93652' }} />,
          });
      }
    })
  };

  //点击确认付款
  handleConfirm = () => {
    this.setState({confirmLoading: true});
    if(this.state.status === 'prending_pay' && this.checkFunctionProfiles('pay.choice.banknum', true)){
      this.setState({ showCompanyBank: true })
    } else {
      this.submit();
    }
  };

  importOfferFile = () =>{
    this.getList();
  };

  handleConfirmBank = (data) => {
    this.setState({ showCompanyBank: false, confirmLoading: false });
    this.confirmSuccess(true,data);
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page =  pagination.current;
    let sortDTOs = [];
    if(sorter.order){
      let temp = {
        property: sorter.columnKey,
        direction: sorter.order === 'ascend' ? 'ASC' : 'DESC'
      };
      sortDTOs.push(temp);
    }
    this.setState({
      page: page - 1,
      sortDTOs
    }, () => {
      this.getList();
    })
  };

  //取消支付
  handleCancelPay = () => {
    this.setState({buttonCancel: true});
    confirmPaymentService.cancelPayment(this.state.status, this.getSubmitData(),true).then(() => {
      this.setState({cancelPayModal: true, buttonCancel: false});
    }).catch((e) => {
      message.error(e.response.data.message);
      this.setState({buttonCancel: false})
    });
  };

  //取消支付
  handleCancel = () => {
    const { getFieldsValue } = this.props.form;
    let reason = getFieldsValue()['reason'];
    if(reason && reason !== ''){
      let params =  this.getSubmitData();
      params.comment = reason;
      this.setState({cancelLoading: true});
      confirmPaymentService.cancelPayment(this.state.status,params,false).then(() => {
        this.setState({cancelPayModal: false,cancelLoading: false});
        this.confirmSuccess(false);
      }).catch((e) => {
        message.error(e.response.data.message);
        this.setState({cancelPayModal: false,cancelLoading: false});
      });
    }else{
      message.error(messages('financial-management.key570')/*请输入理由*/);
    }
  };

  handleChangePayType = (val) => {
    this.setState({payeeType: Number(val),payeeId: []});
  };

  handleDepartment = (value) => {
    this.setState({departmentOids: value});
  };

  handleUserOrVendor = (value) => {
    this.setState({payeeId:value});
  };

  render(){
    const { nowType,searchForm, buttonRoleSwitch, columns, data, loading, pagination, selectedDataNum, status,
      confirmLoading, rowSelection, showCompanyBank,dropDownSelectedKeys, selectedDataItems, cancelPayModal,
      cancelLoading, buttonCancel, payeeType, departmentOids, payeeId, allPageRecord } = this.state;
    let totalObject = {};
    const { getFieldDecorator } = this.props.form;
    selectedDataItems.map(item => {
      totalObject[item.currencyCode] ? totalObject[item.currencyCode] += parseFloat(this.filterMoney(item.realPaymentAmount,queryCurrencyPrecision(item.currencyCode),true).replace(/,/mg,'')) : totalObject[item.currencyCode] = parseFloat(this.filterMoney(item.realPaymentAmount,queryCurrencyPrecision(item.currencyCode),true).replace(/,/mg,''));
    });
    const rightContent = (
      <div>
        <h3>{messages('components.key662',{arg1:messages('components.key505'/*Excel电子表格*/)}/*上传{arg1}*/)}</h3>
        1.{messages('financial-management.key94')/*点击【选择文件】按钮*/}<br/>
        2.{messages('components.key663',{arg1:messages('components.key505'/*Excel电子表格*/)}/*选择你刚更新过的{arg1}，并点击确定*/)}<br/>
      </div>
    );
    return (
      <div className="confirm-payment">
        <Tabs type="card" onChange={this.onChangeTabs} defaultActiveKey={status}>
          {this.renderTabs()}
        </Tabs>
        <SearchArea wrappedComponentRef={inst => this.formRef = inst}
                    searchForm={searchForm}
                    submitHandle={this.search}
                    clearHandle={this.clear}
                    isReturnLabel={true}
                    extraFieldsIndex={6}
                    extraFields={[
                      <div>
                        <div className={'extra-title'}>
                          <Col span={6}>{messages('financial-management.key619')/*类型*/}</Col>
                          <Col span={16} offset={2}>{messages('financial-management.key590')/*收款方*/}</Col>
                        </div>
                        <div>
                          <Col span={6}>
                            <Select placeholder={messages('common.please.select')} onChange={this.handleChangePayType} value={payeeType ? String(payeeType) : undefined}>
                              <Option key={'1001'}>{messages('financial-management.key307')/*供应商*/}</Option>
                              <Option key={'1002'}>{messages('financial-management.key164')/*员工*/}</Option>
                            </Select>
                          </Col>
                          <Col span={16} offset={2}>
                            <Chooser type={payeeType === 1002 ? 'finance_user' : 'finance_vendor'}
                                     single={true}
                                     onChange={this.handleUserOrVendor}
                                     valueKey="id"
                                     disabled={!payeeType}
                                     value={payeeId}
                                     labelKey={payeeType === 1002 ? "fullName" : 'venNickname'}
                                     showClear
                                     placeholder={messages('common.select')/*请选择*/}/>
                          </Col>
                        </div>
                      </div>,
                      <div>
                        <div className={'extra-title'}>{messages('financial-management.key448')/*部门*/}</div>
                        <div>
                          <DepartmentPicker placeholder={messages('common.please.select')}
                                            type='department'
                                            related
                                            value={departmentOids}
                                            onChange={this.handleDepartment}
                                            valueKey="departmentOid"
                                            labelKey="name"/>
                        </div>
                      </div>
                    ]}
                    eventHandle={this.searchEventHandle}/>
        <div className="divider"/>
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total1',{total:pagination.total}/*共 {pagination.total} 条数据*/)}
            {status !== 'pay_finished' && status !== 'pay_cancel' &&
            <span>/{messages('common.total.selected', {total: selectedDataNum}/*已选{selectedDataNum}条*/)}</span>
            }
            {
              selectedDataNum > 0 && dropDownSelectedKeys === 'CURRENT_PAGE' &&
              <span className="show-money">
                ,{messages('financial-management.key75'/*合计金额*/)}&nbsp;&nbsp;
                {
                  Object.keys(totalObject).map(item => {
                    return <span className="money-style">{item}{this.filterMoney(totalObject[item],queryCurrencyPrecision(item),true)}&nbsp;&nbsp;</span>
                  })
                }
              </span>
            }
          </div>
          <div className="table-header-buttons">
            {
              status !== 'pay_finished' && status !== 'pay_cancel' && buttonRoleSwitch &&
              <Dropdown overlay={this.renderDropDown()} placement="bottomCenter">
                <Button>{dropDownSelectedKeys === 'CURRENT_PAGE' && messages('financial-management.key177'/*全选当页*/) || messages('financial-management.key178'/*全选全部*/)}</Button>
              </Dropdown>
            }
            { (status !== 'pay_finished' && status !== 'pay_cancel' && buttonRoleSwitch) &&
              <Button type="primary" onClick={this.handleConfirm} disabled={selectedDataNum === 0} loading={confirmLoading}>{status === 'pay_in_process' ? messages('financial-management.key180'/*确认已付款*/)  : messages('financial-management.key181'/*确认付款*/) }</Button>
            }
            { status  === 'pay_in_process' && buttonRoleSwitch &&
            <ImportModal buttonName={messages('financial-management.key183')}
                         title={messages('financial-management.key183')}
                         hasErrInfo={false}
                         downLinks={null}
                         leftContent={null}
                         rightContent={rightContent}
                         uploadUrl={`${config.baseUrl}/api/reimbursement/batch/paid/confirm/by/document`}
                         onCancel={this.importOfferFile}/>
            }
            { status  !== 'pay_finished' && status !== 'pay_cancel' && buttonRoleSwitch && nowType === 'INVOICE' &&
            this.checkFunctionProfiles(['finance.payment.cancel'], [true]) && <Button onClick={this.handleCancelPay} disabled={selectedDataNum === 0} loading={buttonCancel}>{messages('financial-management.key571')/*取消支付*/}</Button>}
          </div>
        </div>
        <ResizeTable
          rowKey={record => record.id}
          loading={loading}
          rowSelection={(status !== 'pay_finished' && status !== 'pay_cancel' && buttonRoleSwitch) ? rowSelection : window.ISIE9 ? {} : undefined}
          pagination={pagination}
          columns={columns}
          expandedRowRender={this.renderAllExpandedRow}
          onChange={this.handleTableChange}
          onRow={record => ({ onClick: () => this.handleRowClick(record) })}
          rowClassName={ record => record.printFree ||  record.warningList ? '' : 'finance-payment-reject' }
          bordered
          dataSource={data}
        />
        <Modal onOk={this.handleCancel}
               onCancel={() => {this.setState({cancelPayModal: false})}}
               okText={messages("common.ok")}
               cancelText={messages("common.cancel")}
               confirmLoading={cancelLoading}
               visible={cancelPayModal}
               closable={false}>
          <div>
            <Icon type="exclamation-circle" style={{color:"#F7C243",fontSize:"30",float:"left"}}/><span style={{lineHeight:"30px",fontSize:"20",marginLeft:"10px"}}>{messages('financial-management.key572')/*确定取消支付吗*/}?</span>
            <Form onSubmit={this.handleCancel} style={{marginTop:'20px'}}>
              <FormItem label={messages('financial-management.key573')/*理由*/} labelCol={{span: 6}} wrapperCol={{ span: 14, offset: 1 }} style={{marginBottom:'0px'}}>
                {getFieldDecorator('reason',{
                  rules: [{
                    required: true,
                    message: messages('financial-management.key570')/*请输入理由*/
                  }]
                })(
                  <TextArea rows={4} placeholder={messages('common.please.enter')} style={{resize: 'none'}}/>
                )}
              </FormItem>
            </Form>
          </div>
        </Modal>
        <CompanyBankSelector visible={showCompanyBank}
                             selectedDataItems={selectedDataItems.length ? selectedDataItems : allPageRecord}
                             data={this.getSubmitData()}
                             onOk={data => this.handleConfirmBank(data)}
                             onCancel={() => this.setState({showCompanyBank: false, confirmLoading: false})}
                             status={status}/>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    companyConfiguration: state.login.companyConfiguration,
    financePayment: state.cache.financePayment,
    extraSearch: state.cache.extraSearch
  }
}
ConfirmPayment.contextTypes = {
  router: React.PropTypes.object
};

const WrappedConfirmPayment = Form.create()(ConfirmPayment);
export default connect(mapStateToProps)(WrappedConfirmPayment);
